import * as React from 'react';
import { topicDetailApi } from '../../config/api';
import { Spin } from 'antd';
import * as types from '../../config/types_index'

class TopicShow extends React.Component<any, any> {
	constructor(props: any) {
		super(props);
		this.state = {
			id: props.match.params.id,
			topic: {},
			loading: true
		}
	}

	componentDidMount() {
		this.getData()
	}

	getData = () => {
		topicDetailApi(this.state.id).then((data: types.topicDetailData) => {
			console.log(data)
			if (data.success) {
				this.setState({
					loading: false,
					topic: data.data
				})
			}
		})
	}

	replyTemplate = (reply: types.Reply, index: number) => {
		return(
			<div key={index} className={'topic-detail-reply-template'}>
				<div className={'author-avatar-container'}>
					<img src={reply.author.avatar_url} className={'author-avatar'} />
				</div>
				<div style={{flex: 1}} dangerouslySetInnerHTML={{__html: reply.content}} />
			</div>
		)
	}

	render() {
		const { loading, topic } = this.state
		return (
			<div className={'topic-detail-container'}>
				{loading ? (<Spin />) : (null)}
				<div className={'topic-detail-title'}>
					<h2>{topic.title}</h2>
				</div>

				<div 
					className={'topic-detail-content'}
					dangerouslySetInnerHTML={{__html: topic.content}}
				/>

				<div className={'topic-detail-reply'}>
					{topic.replies && topic.replies.map((reply: types.Reply, index: number) => {
						return this.replyTemplate(reply, index)
					})}
				</div>		
			</div>
		)
	}
}

export default TopicShow